import React, { useEffect, useState } from 'react';
import { Select, message, Space, Input, Button } from 'antd';
import Icon from '@/components/layout/Icon';
import { newBranchApi, getBranchesApi } from '@/request/gitlab';

const SelectAdd = (props) => {
  const { projects, projectId, ...otherProps } = props;
  const search = (input, option) => `${String(option.name)}`.toLowerCase().indexOf(input.toLowerCase()) >= 0;
  const [v, setV] = useState('');
  const [branches, setBranches] = useState<any[]>([]); // 分支列表

  const onChange = (e) => {
    setV(e.target.value);
  };

  // 查找主分支
  const getMainBranch = (project) => {
    const p: any = projects.filter((item: any) => item.id === project)[0];
    return p ? p.default_branch : 'master';
  };

  // 递归获取数据
  const whileGet = async (id) => {
    let result = [];
    async function anonymous(per_page, page) {
      const ret: any = await getBranchesApi({ id, per_page, page });
      if (ret.length === 100) {
        result = result.concat(ret);
        let p = page;
        await anonymous(100, (p += 1));
      } else {
        result = result.concat(ret);
      }
    }
    await anonymous(100, 1);
    console.log(result.length, 'result');
    return result;
  };

  const getBranchesList = async (id) => {
    try {
      const r = await whileGet(id);
      console.log(r.length);
      setBranches(r);
    } catch (err: any) {
      console.log(err);
    }
  };

  useEffect(() => {
    if (projectId) {
      getBranchesList(projectId);
    }
  }, [projectId]);

  const onOk = async () => {
    if (!projectId) {
      message.error('请先选择项目');
      return;
    }
    if (!v) {
      message.error('请输入分支名称');
      return;
    }
    const mainBranch = getMainBranch(projectId);
    const params = {
      id: projectId,
      ref: mainBranch,
      branch: v,
    };
    try {
      const res: any = await newBranchApi(params);
      if (res) {
        message.success('创建分支成功');
        setV('');
        setBranches([...branches, res]);
      }
    } catch (err: any) {
      console.log(err.message);
    }
  };

  return (
    <Select
      placeholder="请选择开发分支"
      options={branches}
      filterOption={search}
      showSearch
      fieldNames={{ label: 'name', value: 'name' }}
      {...otherProps}
      dropdownRender={(menu) => (
        <>
          {menu}
          <div className="flex" style={{ padding: '12px 0' }}>
            <Input style={{ flex: 'auto', marginRight: '10px' }} placeholder="请输入新的分支名称" onChange={onChange} />
            <Button
              className="flex"
              type="primary"
              icon={<Icon src="/images/add.png" style={{ marginRight: '4px' }} width={16} height={16} />}
              onClick={() => {
                onOk();
              }}
            >
              新建分支
            </Button>
          </div>
        </>
      )}
    />
  );
};

export default SelectAdd;
